package com.bosssoft.ct.redis.demo1.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author ChenTong
 * @version 1.0
 * @description redis业务
 * @date 2020/6/18 15:00
 * @modified
 **/
@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private JedisPool jedisPool;

    public  Jedis getJedis(){
        return jedisPool.getResource();
    }


    public <T> T get(String key,Class<T> clazz){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String str = jedis.get(key);
            return this.stringToBean(str, clazz);
        }finally {
            this.returnToPool(jedis);
        }
    }

    public <T> boolean set(int expire,String key,T value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String stringValue = beanToString(value);
            if (stringValue==null||stringValue.length()<=0)
                return false;
            if (expire<=0){
                log.info("jedis set :{}",jedis.set(key,stringValue));
            }else {
                log.info("jedis setex :{}",jedis.setex(key,expire,stringValue));
            }
            return true;
        }finally {
            returnToPool(jedis);
        }
    }

    public boolean del(String ... key){
        if (null==key||key.length<=0) return false;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
            return true;
        }finally {
            returnToPool(jedis);
        }

    }

    private void returnToPool(Jedis jedis){
        if(jedis!=null)
            jedis.close();
    }

    private <T> T stringToBean(String str,Class<T> clazz){
        if(str==null||str.length()<=0||clazz==null)
            return null;
        if (clazz == int.class||clazz==Integer.class){
            return (T) Integer.valueOf(str);
        }else if(clazz==String.class){
            return (T) str;
        }else if(clazz==long.class||clazz== Long.class){
            return (T)Long.valueOf(str);
        }else{
            return JSON.toJavaObject(JSON.parseObject(str),clazz);
        }
    }

    private <T> String beanToString(T value) {
        if (value==null)
            return null;
        Class<?> clazz = value.getClass();
        if (clazz == Integer.class){
            return ""+value;
        }else if(clazz == String.class){
            return (String) value;
        }else if(clazz == Long.class){
            return ""+value;
        }else{
            return JSON.toJSONString(value);
        }
    }

}
